package org.xurui.bsj.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.springframework.util.StringUtils;
import org.xurui.bsj.protocol.cache.ConcurrentMapCache;
import org.xurui.bsj.protocol.command.CmdCodec;
import org.xurui.bsj.protocol.enums.CommandEnum;
import org.xurui.bsj.protocol.msg.BsjMessage;
import org.xurui.bsj.protocol.msg.BsjMessageBuilder;
import org.xurui.bsj.protocol.utils.ArrayUtils;
import org.xurui.bsj.protocol.utils.BinaryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4.2.6.远程终端操作
 */
@Slf4j
public class CmdCodec_REMOTE_OPERATE_TERMINAL implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.REMOTE_OPERATE_TERMINAL.name().equals(cmd);
    }

    @Override
    public List<DeviceMessage> parsePayload(BsjMessage payload, FromDeviceMessageContext context) {
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000,REMOTE_OPERATE_TERMINAL,2,20180528111820,1,0]
        /**
         * 报文体格式：应答状态, 应答状态按位划分,每位中1代表该位所代表的操作没有成功完成,0 代表完成, 若应答状态 返回0,则代表所有请求的远程终端操作都已成功完成
         */
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        report.setDeviceId(payload.getHeader().getDeviceNo());
        report.setFunctionId(payload.getHeader().getCmd());
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(payload.getHeader().getOrderNo());
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = payload.getHeader().getOrderNo();
        }
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        String tempBody = payload.getTempBody();
        String[] tempBodyArr = tempBody.split("@");
        //properties.put("header", FastBeanCopier.copy(payload.getHeader(), HashMap::new));
        properties.put("header", payload.getHeader().toMap());
        //应答状态(0=设置成功;1=设置异常;)
        properties.put("responseStatus", ArrayUtils.getStrByIndex(tempBodyArr,0));
        report.setOutput(properties);
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //例子：[782878287828782,89860802012080190008,202110181537090052,REMOTE_OPERATE_TERMINAL,1,20211018153709,3,1@0]
        /**
         * 报文体格式： 重启终端
         *            @恢复除平台地址以外的出厂设置
         * 字段说明: 1.重启终端: 0=不执行，1=执行
         *         2.恢复除平台地址以外的出厂设置: 0=不执行，1=执行
         */
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String  restartTerminal="";
            if(paramsMap.get("restartTerminal")!=null && !paramsMap.get("restartTerminal").equals("")) {
                restartTerminal=paramsMap.get("restartTerminal").toString();
            }

            String factorySet="";
            if(paramsMap.get("factorySet")!=null && !paramsMap.get("factorySet").equals("")) {
                factorySet=paramsMap.get("factorySet").toString();
            }

            if(StringUtils.isEmpty(restartTerminal)){
                log.error("重启终端为空请重新填写");
                return null;
            }
            if(StringUtils.isEmpty(factorySet)){
                log.error("恢复除平台地址以外的出厂设置为空请重新填写");
                return null;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(restartTerminal);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(factorySet);

            return BsjMessageBuilder.create().buildBsjFunctionInvoickMessage(m,sb.toString());
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.REMOTE_OPERATE_TERMINAL.name(),message);
            }
            return null;
        }

    }
}
